package cc.laop.ftp;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.util.Properties;

/**
 * @Auther: Pengpeng
 * @Date: create in 2018/1/5 11:44
 * @Description:
 */
public class FtpUtils {

    private static ChannelSftp channel = null;

    public static void initChannel() {
        try {
            JSch jsch = new JSch(); // 创建JSch对象
            Session session = jsch.getSession(user, url, port); // 根据用户名，主机ip，端口获取一个Session对象
            session.setPassword(pwd); // 设置密码
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config); // 为Session对象设置properties
            session.setTimeout(10000); // 设置timeout时间
            session.connect(); // 通过Session建立链接
            channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void upload(String local, String remote) throws SftpException {
        channel.put(local, remote, ChannelSftp.OVERWRITE);
    }


    public static void download(String remote, String local) throws SftpException {
        channel.get(remote, local);
    }

    public static void mkdir(String filepath) throws SftpException {
        try {
            channel.cd(filepath);
        } catch (SftpException e) {
            channel.mkdir(filepath);
        }
    }

    public static void close() {
        channel.disconnect();
    }


    private static String url = "119.23.73.73";
    private static int port = 8909;
    private static String user = "root";
    private static String pwd = "peng.1989";
}
